package com.firebird.fb.Listener;

import java.util.HashMap;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FbCmsSessionListener implements HttpSessionListener {

	private final Log logger = LogFactory.getLog(this.getClass());
	private static final long serialVersionUID = 1L;

	private final static String LOGINCODE = "login_code";
	private final static String ECSCSESSIONFLAG = "fbcms_session_flag";

	public FbCmsSessionListener() {

	}

	/**
	 * 捕获会话创建的事件,把包含用户登陆信息的会话存入内部全局会话列表中
	 * @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
	 */
	@SuppressWarnings("unchecked")
	public synchronized void sessionCreated(HttpSessionEvent se) {
		try {
			//获取内部全局会话列表   
			HashMap mon = (HashMap<String, HttpSession>) se.getSession().getServletContext().getAttribute(ECSCSESSIONFLAG);
			if (mon == null) {
				//全局会话列表不存在就创建之 
				mon = new HashMap();   
				se.getSession().getServletContext().setAttribute(ECSCSESSIONFLAG, mon);
			}
			se.getSession().setMaxInactiveInterval(600);
			mon.put(se.getSession().getId(), se.getSession());

			logger.warn("会话建立，sessionID是:" + se.getSession().getId());
		} catch (Exception e) {
			logger.warn("SessionListener.sessionCreated Exception:", e);
		}
	}

	/**
	 * 捕获会话销毁的事件，把用户的会话从内部全局会话列表中删除掉   
	 * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
	 */
	@SuppressWarnings("unchecked")
	public synchronized void sessionDestroyed(HttpSessionEvent se) {
		try {
			//从即将销毁的会话中获取用户名
			String loginCode = (String) se.getSession().getAttribute(LOGINCODE);
			HashMap mon = (HashMap) se.getSession().getServletContext().getAttribute(ECSCSESSIONFLAG);
			if (mon != null && mon.containsKey(se.getSession().getId())){
				//把用户的会话从内部全局会话列表中删除掉
				mon.remove(se.getSession().getId());
			}
			logger.warn("会话失效，sessionID是:" +  se.getSession().getId());
			if (loginCode != null){
				logger.warn("登陆失效，号码为:" + loginCode);
			}
		} catch (Exception e) {
			logger.warn("SessionListener.sessionDestroyed Exception:", e);
		}
	}

}